package com.atguigu.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsConfigurationSource;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

@Configuration
public class CorsConfig {
    //创建允许跨域的过滤器到容器中
    @Bean
    public CorsWebFilter corsWebFilter(){
        //允许跨域的配置对象：
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);//是否允许请求报文携带cookie
        config.addAllowedHeader("*"); //允许跨域请求携带的请求头
        config.addAllowedMethod("*"); //允许跨域访问使用的请求方式
        config.addAllowedOrigin("*"); //允许跨域访问的域名(localhost:3000的页面发起异步请求访问网关，*可以通配 localhost:3000)
        source.registerCorsConfiguration("/**",config); //所有的请求 配置允许跨域
        //创建过滤器对象
        CorsWebFilter corsWebFilter = new CorsWebFilter(source);
        return corsWebFilter;
    }
}
